<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class PollsController extends AppController {

    var $layout = 'default';
    var $uses = array(
        'Option'
    );
    var $scripts = array('jquery-1.7.2.min.js', 'custom_v1.24.js');
    function vote() {
        $form   = $this->params['form'];

        if((!$this->Cookie->read('voted'))){
            $conditions = array(
                '`Option`.`vote_times`' => '`Option`.`vote_times` + 1',
            );        
            $this->Option->updateAll($conditions, array('Option.id' => intval($form['optionid'])));
            $this->Cookie->write('voted','1');
            echo '1';
        }else{
            echo '0';
        }
        
        exit;
    }
    function result(){
        $this->set('title_for_layout', 'Kết quả bình chọn');
        $conditions = array(
            'Option.published' => 1,
            'Option.poll_id'   =>  1,
        );
        $data = $this->Option->find('first', array(
                    'fields' => array('SUM(Option.vote_times) AS total_votes'),
                    'conditions' => $conditions,
                    'order' => array(
                        'Option.ordering' => 'ASC'
                    )
        ));

        $sum_vote   =   $data[0]['total_votes'];

        
        $data = $this->Option->find('all', array(
                    'fields' => array('Option.id', 'Option.title', 'Option.vote_times', 'Option.url'),
                    'conditions' => $conditions,
                    'order' => array(
                        'Option.ordering' => 'ASC'
                    )
        ));
        foreach($data AS &$row){
            $percent        =   round(($row['Option']['vote_times'] / $sum_vote ) * 100, 1);
            $chart_width    =   210 /100 * $percent;
            $row['Option']['chart_width']   =   $chart_width;
            $row['Option']['percent']       =   $percent;
        }
        $this->set('data', $data);
    }
}

?>
